
import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:rfid/entity/place_entity.dart';
import 'package:rfid/util/toast_util.dart';
import '../entity/book_entity.dart';
import '../entity/current_task_entity.dart';
import '../entity/setting_entity.dart';
import '../event/inventory_rfid_event.dart';
import '../event/lock_state_event.dart';
import '../hive/hive_helper.dart';
import '../http/api.dart';
import '../main.dart';
import '../socket/socket.dart';
import '../util/analysis_book_rule.dart';
import '../widget/device_name_widget.dart';
import '../widget/focus_killer.dart';


class StackBook extends StatefulWidget {
  const StackBook({Key? key}) : super(key: key);

  @override
  State<StackBook> createState() => _StackBookState();
}

class _StackBookState extends State<StackBook> {


  late List<SettingEntityReader> _lists;
  final RxList<SettingEntityReader> _list = RxList();
  var pageIndex = 1;
  var pageSize = 32;

  StreamSubscription? lockSubscription;
  StreamSubscription? actionSubscription;

  RxList<BookEntity> bookList = RxList();

  @override
  initState() {
    super.initState();

    lockSubscription = eventFactory.on<LockStateEvent>().listen((event) {
      if(event.state == 1){
        timer.cancel();
        BotToast.showLoading();
        if(settingEntity.isUltra!){
          socketHelper.add(inventoryUhfRfid(readerIp: currentTask.readerIp!,ant: currentTask.ant!,count: settingEntity.scanTime!));
        }else{
          socketHelper.add(inventoryHfRfid(readerIp: currentTask.readerIp!,ant: currentTask.ant!,count: settingEntity.scanTime!,blockStart:settingEntity.blockStart,blockCount:settingEntity.blockCount));
        }
      }
    });

    actionSubscription = eventFactory.on<InventoryRfidEvent>().listen((event) async {
      BotToast.closeAllLoading();
      var entity = event.entity;
      if(entity.list != null) {
        bookList.clear();
        var books = bookQueryByDoorNo(currentTask.doorNo!).where((element) => element.statue==0);
        for (var item in books) {
          item.stackStatus = 2;
          bookList.add(item);
        }
        for (var item in entity.list!) {
          try{
            var id = '';
            if(settingEntity.isUltra!){
              id = item.epc!;
            }else{
              id = item.blockData!;
            }
            // var length = int.parse(id.substring(0,2));
            // var bookNo = id.substring(2, length+2);
            var bookNo = analysisBookRule(id);
            await getBook(bookNo);
          }catch(e){
            var bk = BookEntity();
            if(settingEntity.isUltra!){
              bk.no =  item.epc;
            }else{
              bk.no = item.blockData;
            }
            bk.doorNo = currentTask.doorNo!;
            bk.stackStatus = -1;
            bookList.add(bk);
            toastWarn('条码号异常');
          }
        }

        if(Get.isDialogOpen != null && Get.isDialogOpen!){

          Get.back();
        }
        _resultListDialog();
      }
    });

    if(settingEntity.reader != null && settingEntity.reader!.isNotEmpty){
      _lists = settingEntity.reader!.where((element) => element.state == 0).toList();
      _subList();
    }else{
      toastWarn('未配置格口');
    }
  }

  Future getBook(bookNo) async {
    var bk = bookQuery(bookNo);

    if(bk != null && bk.doorNo == currentTask.doorNo && bk.statue == 0){
      bookList.removeWhere((element) => element.no == bookNo);
      bk.stackStatus = 1;
      bookList.add(bk);
    }

    if(bk != null && bk.statue == 1){
      bk.doorNo = currentTask.doorNo!;
      bk.stackStatus = 0;
      bookList.add(bk);
    }

    if(bk == null){
      var data = await findBook(bookNo);
      if(data != null){
        // var book = await searchBook(data);
        // if(book != null){
        data.doorNo = currentTask.doorNo!;
        data.stackStatus = 0;
        bookList.add(data);
        // }
      }else{
        var bk = BookEntity();
        bk.no = bookNo;
        bk.doorNo = currentTask.doorNo!;
        bk.stackStatus = -2;
        bookList.add(bk);
      }
    }

  }


  @override
  void dispose() {
    super.dispose();
    actionSubscription?.cancel();
    actionSubscription = null;
    lockSubscription?.cancel();
    lockSubscription = null;
  }

  _subList(){

    if(pageIndex<1){
      pageIndex = 1;
      toastWarn('已经是第一页');
    }
    if(_lists.length > pageIndex*pageSize){
      _list.clear();
      _list.addAll(_lists.sublist((pageIndex-1)*pageSize,pageIndex*pageSize));
    }else if(_lists.length <= pageIndex*pageSize && _lists.length > (pageIndex-1)*pageSize){
      _list.clear();
      _list.addAll(_lists.sublist((pageIndex-1)*pageSize,_lists.length));
    }else{
      pageIndex--;
      toastWarn('已经是最后一页');
    }

  }


  _appBar(){
    return Container(
      width: double.infinity,
      height: 42.h,
      alignment: Alignment.center,
      padding: const EdgeInsets.only(left: 20,right: 20).w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          deviceNameWidget(),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              focusKiller(),
              Text(" ",style: TextStyle(color: Colors.white,fontSize: 12.sp),)
            ],
          )

        ],
      ),
    );
  }

  _title(){
    return Container(
      margin: EdgeInsets.only(top: 20.h,left: 20.w,right: 20.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          InkWell(
            onTap: (){
              currentTask.clear();
              Get.back();
            },
            child: _image("assets/images/back.png",60.w,23.h),
          ),
          _image("assets/images/type_door_title.jpg",90.w,21.h),
          Text("   ",style: TextStyle(color: Colors.white,fontSize: 12.sp),)
        ],
      )
    );
  }

  _divider(){
    return Divider(
      height: 0.5.h, // Divider 组件高度
      indent: 4.w, // 分割线左侧间距
      endIndent: 4.w, // 分割线右侧间距
      color: const Color.fromRGBO(86, 169, 255, 1),
    );
  }

  _listLabel(){
    return Container(
        padding: EdgeInsets.only(top: 2.h,bottom: 2.h),
        decoration: const BoxDecoration(
          color: Colors.white,
        ),
        child: Row(
          // mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _label('序号',50.w),
            _label('图书条码号',105.w),
            _label('图书名称',105.w),
            _label('状态',50.w),
          ],
        )
    );
  }

  _label(text,width){
    return Container(
      width: width,
      alignment: Alignment.center,
      child: Text(text,style: TextStyle(color: Colors.blueAccent,fontSize: 10.sp),textAlign: TextAlign.center,),
    );
  }

  _listTitle(){
    return Container(
      // width: 300.w,
      height: 20.h,
      decoration: BoxDecoration(
        color: const Color.fromRGBO(86, 169, 255, 1),
        borderRadius: BorderRadius.only(topLeft:Radius.circular(4.r),topRight: Radius.circular(4.r)),
      ),
      alignment: Alignment.center,
      child: Text('图书清单',style: TextStyle(color: Colors.white,fontSize: 10.sp,fontWeight: FontWeight.bold),),
    );
  }

  _item(text,width,{Color color = Colors.black}){
    return Container(
      width: width,
      alignment: Alignment.center,
      child: Text(text,style: TextStyle(color: color,fontSize: 8.sp),textAlign: TextAlign.center,),
    );
  }

  _listItem(list,index){
    var item = list[index];

    return Container(
        padding: EdgeInsets.only(top: 2.h,bottom: 2.h),
        child: Row(
          // mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _item('${index+1}',50.w),
            _item('${item.no}',105.w),
            _item('${item.mainTitle}',105.w),
            item.stackStatus == 0?_item('上架',50.w,color: Colors.blue):item.stackStatus == 1?
              _item('在架',50.w):item.stackStatus == 2?_item('下架',50.w,color: Colors.red):
            item.stackStatus == -1?_item('条码号错误',50.w,color: Colors.deepOrangeAccent):_item('图书未注册',50.w,color: Colors.deepOrangeAccent)
          ],
        )
    );
  }

  _bList(){
    return Obx(() => Expanded(child: ListView.separated(
      itemBuilder: (context, index) {
        return _listItem(bookList,index);
      },
      itemCount: bookList.length,
      separatorBuilder: (BuildContext context, int index) {
        return Divider(
          height: 0.5.h, // Divider 组件高度
          // thickness: 5, // 分割线线宽，分割线居于 Divider 中心
          indent: 4.w, // 分割线左侧间距
          endIndent: 4.w, // 分割线右侧间距
          color: Colors.grey,
        );
      },
    )));
  }

  _totalWidget(){

    return Obx(() => Row(
      children: [
        Text('   在架${ bookList.where((e) => e.stackStatus==1).length}本   ',style: TextStyle(fontSize: 8.sp)),
        Text('下架${ bookList.where((e) => e.stackStatus==2).length}本   ',style: TextStyle(color: Colors.red,fontSize: 8.sp),),
        Text('上架${ bookList.where((e) => e.stackStatus==0).length}本   ',style: TextStyle(color: Colors.blue,fontSize: 8.sp),),
        Text('条码号错误${ bookList.where((e) => e.stackStatus==-1).length}本   ',style: TextStyle(color: Colors.deepOrangeAccent,fontSize: 8.sp),),
        Text('图书未注册${ bookList.where((e) => e.stackStatus==-2).length}本   ',style: TextStyle(color: Colors.deepOrangeAccent,fontSize: 8.sp),),
      ],
    ));
  }

  _listWidget(){
    return Container(
      width: 330.w,
      height: 420.h,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
      ),
      child: Column(
        children: [
          _listTitle(),
          _listLabel(),
          _divider(),
          _bList(),
          _totalWidget(),
          SizedBox(height: 5.h,)
        ],
      ),

    );
  }

  _resultListDialog(){
    Get.defaultDialog(
      title: "",
      barrierDismissible: false,
      contentPadding:EdgeInsets.zero,
      titlePadding:EdgeInsets.zero,
      backgroundColor: Colors.transparent,
      content: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _listWidget(),
          SizedBox(height: 10.h,),
          Row(mainAxisAlignment:MainAxisAlignment.center, children: [_open(),_confirm()],)
        ],
      )
    );
  }

  _open(){
    return InkWell(
      onTap: () {
        socketHelper.add(lockOpen(addr: currentTask.addr!, no: currentTask.lock!));

      },
      child:  _image("assets/images/open_button.jpg", 80.w, 36.h),
    );
  }

  _confirm(){
    return InkWell(
      onTap: () {

        var list = [];
        for(var item in bookList){
          if(item.stackStatus == 0){
            item.statue = 0;
            bookInsert(item.no, item);
          }
          if(item.stackStatus == 0 || item.stackStatus == 1){
            list.add(
                PlaceEntity()
                  ..bookNo = item.no
                  ..place = '${settingEntity.index}${currentTask.doorNo?.padLeft(2,'0')}格'
            );
          }
          if(item.stackStatus == 2){
            bookDelete(item.no);
            list.add(
                PlaceEntity()
                  ..bookNo = item.no
                  ..place = ''
            );
          }
        }
        sendPlace(list);
        currentTask.clear();
        if(Get.isDialogOpen != null && Get.isDialogOpen!){
          Get.back();
        }
      },
      child:  _image("assets/images/result_confirm.jpg", 80.w, 36.h),
    );
  }


  _itemBuilder(index){
    var item = _list[index];
    RxBool isClick = RxBool(false);
    return InkWell(
      onTap: (){
        currentTask.task = Task.borrowWithDoor;
        currentTask.addr = item.addr!;
        currentTask.lock = item.lock!;
        currentTask.doorNo = item.doorNo!;
        currentTask.readerIp = item.readerIp!;
        currentTask.ant = item.ant!;
        socketHelper.add(lockOpen(addr: currentTask.addr!, no: currentTask.lock!));
        isClick.value = true;
      },
      child: Stack(
        alignment: Alignment.center,
        children: [
          Obx(() => _image(isClick.value == true?"assets/images/stack.png":"assets/images/door_bg.png", 100.w, 70.h)),
          Text('格口${item.doorNo}',style: TextStyle(color: Colors.blue,fontWeight:FontWeight.bold,fontSize: 8.sp),),
        ],
      ),
    );
  }

  _booksContainer(){
    return Container(
      margin: EdgeInsets.only(left: 20.w,right: 20.w,top: 20.h),
      width: double.infinity,
      height: 460.h,
      child: Obx(() => GridView.builder(
        itemBuilder: (context, index) {
          return _itemBuilder(index);
        },
        itemCount: _list.length,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4,childAspectRatio:1.42,  crossAxisSpacing: 5.w),
      ),)
    );
  }

  _action(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        InkWell(
          onTap: (){
            pageIndex--;
            _subList();
          },
          child:  _image("assets/images/previous.png", 80.w, 36.h),
        ),
        InkWell(
          onTap: (){
            pageIndex++;
            _subList();
          },
          child:   _image("assets/images/next.png", 80.w, 36.h),
        )
      ],
    );
  }


  _image(name,width, height){
    return Image.asset(name,height: height, width: width, fit: BoxFit.fill,);
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          children: [
            _appBar(),
            _title(),
            _booksContainer(),
            _action(),
          ],
        ),
      ),
    );
  }
}

